<template>
  <el-dialog v-if="openForm" v-model="openBoole" :close-on-click-modal="false" :title="typeTitle"
    custom-class="mydialog" width="50%" @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" label-width="140px" size="small">
      <el-row gutter="40">
        <el-col v-if="typeTitle === '变更潜在代理商'" :span="24">
          <el-form-item label="代理编号">
            <el-input v-model="openForm.agentNumber" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="代理商名称" prop="agentName">
            <el-input v-model="openForm.agentName" clearable placeholder="请输入代理商名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所在地区" prop="value">
            <el-cascader v-model="openForm.value" :options="cityList" :popper-append-to-body="false"
              :props="{ value:'regionCode',label:'regionName',expandTrigger: 'hover' }" placeholder="请选择地区"
              style="width:100%" @change="handlCity" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="openForm.address" clearable placeholder="请输入详细地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="userName">
            <el-input v-model="openForm.userName" clearable placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="tel">
            <el-input v-model="openForm.tel" clearable placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="统一社会信用代码" prop="creditCode">
            <el-input v-model="openForm.creditCode" clearable placeholder="请输入统一社会信用代码" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消
        </el-button>
        <!-- <el-button v-if="typeTitle === '新建潜在代理商'" class="border-btn" size="small" style="margin-right: 20px;"
          @click="handlSave">保存并新建
        </el-button> -->
        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  getCurrentInstance,
  inject,
  nextTick,
  reactive,
  ref,
  toRefs,
} from "vue";
import area from "@/utils/area";
import { validateVETel } from "@/utils/validate";

export default {
  name: "AgentDialog",
  props: {
    typeTitle: {
      type: String,
      defaults() {
        return "新建潜在代理商";
      },
    },
    agentType: {
      type: String,
      default: "",
    },
  },
  setup(props, context) {
    //* ************自定义效验**********
    const validateTel = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机码"));
      } else {
        if (validateVETel(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      }
    };
    const validateName = async (rule, value, callback) => {
      if (value === "") {
        callback("请输入代理商名称");
      } else {
        const aaa = await validateVEName(value);
        if (aaa) {
          callback(new Error("代理商名称已存在"));
        } else {
          callback();
        }
      }
    };
    //* ********************************
    const api = inject("api");
    var data = reactive({
      openBoole: false,
      cityList: area,
      openForm: {
        value: null,
        agentNumber: "",
        agentName: "", // 代理商名称
        provinceCode: "", // 省code
        cityCode: "", // 市code
        areaCode: "", // 区code
        address: "", // 详细地址
        userName: "", // 联系人
        tel: "", // 联系电话
        creditCode: "", // 统一信用代征码
        agentType: props.agentType,
      },
      openRef: null,
      rules: {
        agentName: [
          { required: true, validator: validateName, trigger: "blur" },
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        tel: [{ required: true, validator: validateTel, trigger: "blur" }],
        value: [{ required: true, message: "请选择地区", trigger: "change" }],
        creditCode: [
          {
            required: true,
            message: "请输入统一社会信用代码",
            trigger: "blur",
          },
        ],
      },
      num: 0,
    });
    const currentInstance = getCurrentInstance();

    const handlCity = (val) => {
      if (val) {
        data.openForm.provinceCode = val[0];
        data.openForm.cityCode = val[1];
        data.openForm.areaCode = val[2];
        nextTick((_) => {
          data.openRef.clearValidate("provinceCode");
        });
      }
    };

    const validateVEName = async (val) => {
      const paramData = {
        table: "agent",
        column: "agent_name",
        column_data: val,
        id: data.openForm.id ? data.openForm.id : "",
      };
      const booleName = ref(false);
      const res = await api.channelAgent.POTENTIALAGENT_NAME(paramData);
      if (res.code === 0) {
        if (res.data.exist === "1") {
          booleName.value = true;
        } else {
          booleName.value = false;
        }
      } else {
        booleName.value = false;
      }
      return booleName.value;
    };

    const close = () => {
      data.openBoole = false;
      handlRemove();
    };

    const handlRemove = () => {
      data.openForm.provinceCode = "";
      data.openForm.cityCode = "";
      data.openForm.areaCode = "";
      data.openRef.clearValidate();
      data.openRef.resetFields();
    };

    const open = (val, num) => {
      data.openForm = {
        value: null,
        agentNumber: "",
        agentName: "", // 代理商名称
        provinceCode: "", // 省code
        cityCode: "", // 市code
        areaCode: "", // 区code
        address: "", // 详细地址
        userName: "", // 联系人
        tel: "", // 联系电话
        creditCode: "", // 统一信用代征码
        agentType: props.agentType,
      };
      data.openBoole = true;
      if (val) {
        for (const key in data.openForm) {
          data.openForm[key] = val[key];
        }
        data.openForm.id = val.id;
        data.openForm.value = [
          data.openForm.provinceCode,
          data.openForm.cityCode,
          data.openForm.areaCode,
        ];
      }
      if (num) {
        data.num = num;
      }
    };

    // 保存并新建
    const handlSave = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          const dataobj = reactive({
            agentName: data.openForm.agentName, // 代理商名称
            provinceCode: data.openForm.provinceCode, // 省code
            cityCode: data.openForm.cityCode, // 市code
            areaCode: data.openForm.areaCode, // 区code
            address: data.openForm.address, // 详细地址
            userName: data.openForm.userName, // 联系人
            tel: data.openForm.tel, // 联系电话
            creditCode: data.openForm.creditCode, // 统一信用代征码
            agentType: data.openForm.agentType,
          });
          api.channelAgent.POTENTIALAGENT_CREATE(dataobj).then((res) => {
            if (res.code === 0) {
              currentInstance.proxy.customMessage({
                type: "success",
                message: "创建成功",
              });
              context.emit("succsess");
              handlRemove();
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        }
      });
    };

    // 确定
    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          const dataobj = reactive({
            agentName: data.openForm.agentName, // 代理商名称
            provinceCode: data.openForm.provinceCode, // 省code
            cityCode: data.openForm.cityCode, // 市code
            areaCode: data.openForm.areaCode, // 区code
            address: data.openForm.address, // 详细地址
            userName: data.openForm.userName, // 联系人
            tel: data.openForm.tel, // 联系电话
            creditCode: data.openForm.creditCode, // 统一信用代征码
            agentType: data.openForm.agentType,
          });
          const commit = ref(undefined);
          const msgs = ref("");
          if (data.openForm.id) {
            if (data.num === 1) {
              commit.value = api.channelAgent.POTENTIALAGENT_CHANGE;
              msgs.value = "变更成功";
              dataobj.id = data.openForm.id;
            }
            if (data.num === 2) {
              commit.value = api.channelAgent.POTENTIALAGENT_UPDATE;
              msgs.value = "编辑成功";
              dataobj.id = data.openForm.id;
            }
            if (data.num === 3) {
              commit.value = api.editorial.EDITORIAL_CUSTOMER_ENTERPRISE_UPDATE;
              msgs.value = "确认成功";
              dataobj.id = data.openForm.id;
            }
          } else {
            commit.value = api.channelAgent.POTENTIALAGENT_CREATE;
            msgs.value = "创建成功";
          }
          commit.value(dataobj).then((res) => {
            if (res.code === 0) {
              currentInstance.proxy.customMessage({
                type: "success",
                message: msgs.value,
              });
              context.emit("succsess");
              close();
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        }
      });
    };

    return {
      ...toRefs(data),
      close,
      open,
      handlSubmit,
      handlCity,
      handlSave,
      handlRemove,
      validateVEName,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
